<template>
  <div class="default-config-panel">
    <a-tabs v-model:activeKey="activeTab">
      <a-tab-pane key="base" title="基本信息">
        <BaseNodeInfoPanel
          :label="local.label"
          :description="local.description"
          @update:label="(v) => (local.label = v)"
          @update:description="(v) => (local.description = v)"
        />
      </a-tab-pane>

      <a-tab-pane v-if="showExecTarget" key="executor" title="执行目标">
        <div class="exec-target">
          <a-tabs v-model:activeKey="targetType" size="medium">
            <a-tab-pane key="user" title="用户">
              <div class="row">
                <span class="label">执行人</span>
                <a-select
                  v-model="local.executeTarget.users"
                  :options="userOptions"
                  allow-clear
                  multiple
                  placeholder="请选择用户"
                  style="width: 100%"
                />
              </div>
            </a-tab-pane>
            <a-tab-pane key="user_group" title="组织架构">
              <div class="row">
                <span class="label">组织/用户组</span>
                <a-select
                  v-model="local.executeTarget.groups"
                  :options="groupOptions"
                  allow-clear
                  multiple
                  placeholder="请选择组织/用户组"
                  style="width: 100%"
                />
              </div>
            </a-tab-pane>
            <a-tab-pane key="variable" title="变量">
              <div class="row">
                <span class="label">变量</span>
                <div style="flex: 1">
                  <a-dropdown
                    v-model:popupVisible="varSelectVisible"
                    trigger="click"
                    position="bl"
                  >
                    <a-input
                      readonly
                      :model-value="singleVarLabel"
                      placeholder="请选择变量（单选）"
                      @click="varSelectVisible = true"
                    >
                      <template #suffix>
                        <span style="color: var(--color-text-3)">▼</span>
                      </template>
                    </a-input>
                    <template #content>
                      <div class="var-dropdown">
                        <a-tabs size="mini" v-model:activeKey="varActiveTab">
                          <a-tab-pane key="process" title="流程变量">
                            <template
                              v-if="
                                variablesGrouped.process &&
                                variablesGrouped.process.length
                              "
                            >
                              <div class="var-pane">
                                <a-button
                                  v-for="v in variablesGrouped.process"
                                  :key="v.value"
                                  size="mini"
                                  type="text"
                                  class="var-item"
                                  @click="selectVar(v.value)"
                                  >{{ v.label }}</a-button
                                >
                              </div>
                            </template>
                            <div class="var-empty" v-else>暂无流程变量</div>
                          </a-tab-pane>
                          <a-tab-pane key="output" title="出参变量">
                            <template
                              v-if="
                                variablesGrouped.output &&
                                variablesGrouped.output.length
                              "
                            >
                              <div class="var-pane">
                                <a-button
                                  v-for="v in variablesGrouped.output"
                                  :key="v.value"
                                  size="mini"
                                  type="text"
                                  class="var-item"
                                  @click="selectVar(v.value)"
                                  >{{ v.label }}</a-button
                                >
                              </div>
                            </template>
                            <div class="var-empty" v-else>暂无出参变量</div>
                          </a-tab-pane>
                          <a-tab-pane key="system" title="系统变量">
                            <template
                              v-if="
                                variablesGrouped.system &&
                                variablesGrouped.system.length
                              "
                            >
                              <div class="var-pane">
                                <a-button
                                  v-for="v in variablesGrouped.system"
                                  :key="v.value"
                                  size="mini"
                                  type="text"
                                  class="var-item"
                                  @click="selectVar(v.value)"
                                  >{{ v.label }}</a-button
                                >
                              </div>
                            </template>
                            <div class="var-empty" v-else>暂无系统变量</div>
                          </a-tab-pane>
                        </a-tabs>
                      </div>
                    </template>
                  </a-dropdown>
                </div>
              </div>
            </a-tab-pane>
          </a-tabs>
        </div>
      </a-tab-pane>

      <a-tab-pane v-if="showFormRender" key="formRender" title="表单渲染">
        <div class="exec-target">
          <div class="row">
            <span class="label">绑定视图</span>
            <a-select
              v-model="local.formViewId"
              :options="viewOptions"
              :loading="viewLoading"
              allow-clear
              placeholder="请选择视图"
              style="width: 100%"
            />
          </div>
          <div>
            <div class="preview-header">
              <a-divider orientation="left">表单预览</a-divider>
              <a-button
                type="text"
                size="mini"
                @click="showVariablePanel = true"
                >变量</a-button
              >
            </div>
            <div v-if="currentViewUi" style="padding: 8px 0">
              <FormRenderer
                :key="String(local.formViewId || 'none')"
                v-model="formData"
                :schema="currentViewUi"
                :variables="variables"
                :variables-grouped="variablesGrouped"
                :form-config="currentFormConfig"
                :show-variable-trigger="true"
                @open-variable-panel="showVariablePanel = true"
              />
            </div>
            <a-empty
              v-else
              description="所选视图未包含 viewUi 或尚未选择视图"
            />
          </div>
        </div>
      </a-tab-pane>

      <a-tab-pane key="outputs" title="自定义出参">
        <BaseOutputsPanel
          v-model="local.outputs"
          :protected-keys="isApproval ? ['approval'] : []"
        />
      </a-tab-pane>
    </a-tabs>

    <div class="panel-actions">
      <a-button type="primary" size="small" @click="save">保存</a-button>
      <a-button size="small" @click="$emit('close')">关闭</a-button>
    </div>

    <VariablePanel
      v-if="showVariablePanel"
      v-model:variables="variables"
      @close="showVariablePanel = false"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from "vue";
import { Message } from "@arco-design/web-vue";
import { listViewByType } from "@/api/views";
import BaseNodeInfoPanel from "./base/BaseNodeInfoPanel.vue";
import BaseOutputsPanel from "./base/BaseOutputsPanel.vue";
import FormRenderer from "@/components/Form/FormRenderer.vue";
import VariablePanel from "@/components/panel/variablePanel.vue";
import { useWorkflowVariables } from "@/components/workflow/useWorkflowVariables";

const props = defineProps<{ node: any; nodes?: any[] }>();
const emit = defineEmits(["update", "close"]);

const activeTab = ref("base");
// 执行目标类型标签：user / user_group / variable
const targetType = ref<string>("user");

// 切换执行目标标签页时，清空上一个标签页的选择数据
watch(
  () => targetType.value,
  (next, prev) => {
    const et = local.executeTarget as any;
    if (!et) return;
    if (prev === "user") {
      et.users = [];
    } else if (prev === "user_group") {
      et.groups = [];
    } else if (prev === "variable") {
      et.variables = [];
    }
  }
);

const isApproval = computed(() => {
  const cat = props.node?.data?.category;
  const t = (props.node as any)?.type;
  return cat === "approval" || t === "approval";
});

const showExecTarget = computed(() => {
  console.log(props.node?.data);
  const cat = props.node?.data?.category;
  console.log(cat);
  return cat === "approval" || cat === "form";
});

// 人工(form)/审批(approval)/自动化(auto) 显示 “表单渲染”
const showFormRender = computed(() => {
  const cat = props.node?.data?.category;
  return cat === "form" || cat === "approval" || cat === "auto";
});

const local = reactive({
  label: props.node?.data?.label || "",
  description: props.node?.data?.description || "",
  outputs: props.node?.data?.outputs
    ? JSON.parse(JSON.stringify(props.node.data.outputs))
    : [],
  executeTarget: props.node?.data?.executeTarget
    ? JSON.parse(JSON.stringify(props.node.data.executeTarget))
    : {
        mode: "fixed",
        users: [] as Array<string>,
        groups: [] as Array<string>,
        variables: [] as Array<string>,
      },
  formViewId: props.node?.data?.formViewId ?? (undefined as undefined | string),
});

function ensureApprovalDefault() {
  if (!isApproval.value) return;
  const list = Array.isArray(local.outputs)
    ? local.outputs
    : (local.outputs = [] as any);
  const idx = list.findIndex(
    (it: any) => String(it?.key || "").trim() === "approval"
  );
  if (idx === -1) {
    list.unshift({ name: "审批结果", key: "approval", type: "string" });
  } else {
    const cur = list[idx] || {};
    const name = String(cur.name || "").trim() || "审批结果";
    const type = String(cur.type || "").trim() || "string";
    list[idx] = { ...cur, name, key: "approval", type };
  }
}

// 预览表单的双向数据
const formData = ref<Record<string, any>>(
  props.node?.data?.formData ? { ...props.node.data.formData } : {}
);

// 变量管理（来源于 variablePanel.vue）
const variables = ref<any[]>([]);
const showVariablePanel = ref(false);

// 引入共享变量源，并构造成分组传给 FormRenderer
const { processVariables, outputVariables, systemVariables } =
  useWorkflowVariables();
const variablesGrouped = computed(() => ({
  process: (processVariables.value || []).map((v) => ({
    label: v.name,
    value: v.value,
  })),
  output: (outputVariables.value || []).map((v) => ({
    label: v.name,
    value: v.value,
  })),
  system: (systemVariables.value || []).map((v) => ({
    label: v.name,
    value: v.value,
  })),
}));

// 变量值 -> 名称 的映射（用于回显）
const variableLabelMap = computed<Record<string, string>>(() => {
  const map: Record<string, string> = {};
  for (const it of variablesGrouped.value.process || []) {
    map[it.value] = it.label;
  }
  for (const it of variablesGrouped.value.output || []) {
    map[it.value] = it.label;
  }
  for (const it of variablesGrouped.value.system || []) {
    map[it.value] = it.label;
  }
  return map;
});

// 单选变量：以数组形式存储，界面使用单选值代理
const varSelectVisible = ref(false);
const varActiveTab = ref<"process" | "output" | "system">("process");
const singleVarValue = computed<string | undefined>({
  get() {
    const arr = Array.isArray(local.executeTarget?.variables)
      ? (local.executeTarget.variables as string[])
      : [];
    return arr[0] || undefined;
  },
  set(v) {
    if (v) {
      local.executeTarget.variables = [String(v)];
    } else {
      local.executeTarget.variables = [];
    }
  },
});

// 输入框回显文本：优先用映射的名称，未命中则空串
const singleVarLabel = computed<string>(() => {
  return singleVarValue.value;
});

function selectVar(v: string) {
  singleVarValue.value = v;
  varSelectVisible.value = false;
}

// 用户选项（可后续接入接口）
const userOptions = ref([
  { label: "张三", value: "u1" },
  { label: "李四", value: "u2" },
  { label: "王五", value: "u3" },
]);

// 组织/用户组选项（占位，可接入组织接口）
const groupOptions = ref<Array<{ label: string; value: string }>>([
  { label: "研发部", value: "g_dev" },
  { label: "市场部", value: "g_marketing" },
  { label: "财务部", value: "g_finance" },
]);

// 旧 variableOptions 已被 flatVariableOptions 替代

// 视图下拉
const viewOptions = ref<Array<{ label: string; value: string }>>([]);
const viewMap = ref<Record<string, any>>({}); // 缓存原始视图项（用于取 viewUi）
const currentViewUi = computed(() => {
  const id = local.formViewId ? String(local.formViewId) : "";
  const item = id ? viewMap.value[id] : undefined;
  const ui = item?.viewUi ?? item?.ui ?? undefined;
  if (!ui) return undefined;
  return ui; // 可能是字符串或对象，FormRenderer 内部会尝试解析
});
// 从所选视图提取表单配置，供 FormRenderer 对齐布局
const currentFormConfig = computed(() => {
  const id = local.formViewId ? String(local.formViewId) : "";
  const item = id ? viewMap.value[id] : undefined;
  const cfg = item?.allFormConfig || {};
  return {
    labelAlign: cfg.labelAlign || "horizontal",
    labelWidth: Number(cfg.labelWidth ?? 120),
  } as { labelAlign?: "horizontal" | "left" | "right"; labelWidth?: number };
});

// 视图切换时，清空表单数据，防止旧字段/旧值干扰新视图
watch(
  () => local.formViewId,
  () => {
    // 必须操作 ref 的 .value，避免对 ref 本身做 delete 导致响应式错误
    if (!formData.value || typeof formData.value !== "object") {
      formData.value = {};
      return;
    }
    Object.keys(formData.value).forEach(
      (k) => delete (formData.value as any)[k]
    );
  }
);
const viewLoading = ref(false);

async function loadViewOptions() {
  try {
    viewLoading.value = true;
    const category = props.node?.data?.category || "";
    const res: any = await listViewByType(category);
    const list = (res?.data?.records || res?.data || []) as any[];
    const options = list
      .map((it: any) => ({
        label: it?.viewName || it?.name || String(it?.id ?? it?.viewId ?? ""),
        value: String(it?.id ?? it?.viewId ?? it?.value ?? ""),
      }))
      .filter((o) => o.value);
    viewOptions.value = options;
    // 建立映射
    const map: Record<string, any> = {};
    for (const raw of list) {
      const key = String(raw?.id ?? raw?.viewId ?? raw?.value ?? "");
      if (key) map[key] = raw;
    }
    viewMap.value = map;
  } catch (e) {
    console.error("loadViewOptions error", e);
    viewOptions.value = [];
    viewMap.value = {};
  } finally {
    viewLoading.value = false;
  }
}

// —— 将当前节点的输出，同步到全局 outputVariables ——
function syncNodeOutputsToVariables() {
  const rawId = String(props.node?.id || "");
  const rawNodeKey = String((props.node as any)?.data?.nodeKey ?? rawId);
  const nodeKey = rawNodeKey; // 传递用 nodeKey
  const nodeLabel = String(
    local.label || (props.node as any)?.data?.label || ""
  );
  if (!nodeKey) return;

  // 1) 先移除本节点旧变量（id 以 `node-${nodeId}-` 开头）
  const prefix = `node-${rawId}-`;
  outputVariables.value = (outputVariables.value || []).filter(
    (v) => !String(v?.id || "").startsWith(prefix)
  );

  // 2) 再根据当前出参添加
  const list = Array.isArray(local.outputs) ? local.outputs : [];
  for (const it of list) {
    const key = String((it as any)?.key || "").trim();
    const name = String((it as any)?.name || "").trim();
    if (!key || !name) continue;
    const id = `${prefix}${key}`;
    const display = `\${${nodeLabel},${key}}`; // 展示用
    const value = `\${${nodeKey},${key}}`; // 传递用（nodeKey）
    const label = `${name}`;
    outputVariables.value.push({ id, name: label, value, display });
  }
}

// 取消自动同步：仅在点击保存时才同步到全局变量

function save() {
  // 保存前确保审批默认出参存在
  ensureApprovalDefault();

  // 组装各标签的校验器
  const validators: Record<string, () => boolean> = {
    base: () => {
      const nm = String(local.label || "").trim();
      if (!nm) {
        Message.error("请填写节点名称");
        activeTab.value = "base";
        return false;
      }
      const all = Array.isArray(props.nodes) ? (props.nodes as any[]) : [];
      const curId = String(props.node?.id || "");
      const duplicated = all.some(
        (n: any) => String(n?.id || "") !== curId && String(n?.data?.label || "").trim() === nm
      );
      if (duplicated) {
        Message.error("节点名称需全局唯一");
        activeTab.value = "base";
        return false;
      }
      return true;
    },
    executor: () => {
      if (!showExecTarget.value) return true;
      const t = String(targetType.value || "user");
      if (t === "user") {
        const list = Array.isArray(local.executeTarget?.users)
          ? local.executeTarget.users
          : [];
        if (!list.length) {
          Message.error("请选择执行人");
          activeTab.value = "executor";
          return false;
        }
      } else if (t === "user_group") {
        const list = Array.isArray(local.executeTarget?.groups)
          ? local.executeTarget.groups
          : [];
        if (!list.length) {
          Message.error("请选择组织/用户组");
          activeTab.value = "executor";
          return false;
        }
      } else if (t === "variable") {
        const list = Array.isArray(local.executeTarget?.variables)
          ? local.executeTarget.variables
          : [];
        if (!list.length || !String(list[0] || "").trim()) {
          Message.error("请选择变量");
          activeTab.value = "executor";
          return false;
        }
      }
      return true;
    },
    formRender: () => {
      if (!showFormRender.value) return true;
      const vid = local.formViewId;
      if (vid == null || vid === '') {
        Message.error("请选择绑定视图");
        activeTab.value = "formRender";
        return false;
      }
      return true;
    },
    outputs: () => {
      const list = Array.isArray(local.outputs) ? local.outputs : [];
      for (let i = 0; i < list.length; i++) {
        const it: any = list[i] || {};
        const nm = String(it.name ?? "").trim();
        const k = String(it.key ?? "").trim();
        if (!nm || !k) {
          Message.error("自定义出参的名称和Key为必填项");
          activeTab.value = "outputs";
          return false;
        }
      }
      return true;
    },
  };

  // 根据当前激活标签动态排序校验顺序
  const order = [activeTab.value, "base", "executor", "formRender", "outputs"]
    .filter((v, idx, arr) => !!validators[v] && arr.indexOf(v) === idx);
  for (const key of order) {
    const ok = validators[key]();
    if (!ok) return;
  }

  const payload: any = {
    label: String(local.label || "").trim(),
    description: local.description,
    outputs: local.outputs,
  };
  // 仅在保存时，同步当前节点出参到全局 outputVariables
  syncNodeOutputsToVariables();
  if (showExecTarget.value) {
    payload.executeTarget = {
      mode: local.executeTarget?.mode || "fixed",
      users: Array.isArray(local.executeTarget?.users)
        ? local.executeTarget.users
        : [],
      groups: Array.isArray(local.executeTarget?.groups)
        ? local.executeTarget.groups
        : [],
      variables: Array.isArray(local.executeTarget?.variables)
        ? local.executeTarget.variables
        : [],
    };
  }
  if (showFormRender.value) {
    payload.formViewId = local.formViewId ?? undefined;
    payload.formData = formData.value || {};
  }
  emit("update", props.node.id, payload);
  emit("close");
}

watch(
  () => props.node,
  (n) => {
    local.label = n?.data?.label || "";
    local.description = n?.data?.description || "";
    local.outputs = n?.data?.outputs
      ? JSON.parse(JSON.stringify(n.data.outputs))
      : [];
    // 切换到审批节点时补齐默认出参
    ensureApprovalDefault();
    local.executeTarget = n?.data?.executeTarget
      ? JSON.parse(JSON.stringify(n.data.executeTarget))
      : { mode: "fixed", users: [], groups: [], variables: [] };
    // 根据已有数据初始化选中标签
    const hasUsers =
      Array.isArray(local.executeTarget?.users) &&
      local.executeTarget.users.length > 0;
    const hasGroups =
      Array.isArray(local.executeTarget?.groups) &&
      local.executeTarget.groups.length > 0;
    const hasVars =
      Array.isArray(local.executeTarget?.variables) &&
      local.executeTarget.variables.length > 0;
    targetType.value = hasUsers
      ? "user"
      : hasGroups
        ? "user_group"
        : hasVars
          ? "variable"
          : "user";
    local.formViewId = n?.data?.formViewId ?? undefined;
    formData.value = n?.data?.formData ? { ...n.data.formData } : {};

    if (showFormRender.value) {
      loadViewOptions();
    }
  },
  { immediate: true }
);
</script>

<style scoped>
.default-config-panel {
  width: 480px;
  background: var(--color-bg-2, #fff);
  box-shadow: -2px 0 16px rgba(0, 0, 0, 0.08);
  position: fixed;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 100;
  padding: 24px 20px 16px 20px;
  display: flex;
  flex-direction: column;
  color: var(--color-text-1, #333);
}

.exec-target {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.row {
  display: flex;
  align-items: center;
  gap: 12px;
}
.label {
  width: 72px;
  color: var(--color-text-2, #666);
}
.panel-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: auto;
  padding-top: 16px;
  border-top: 1px solid var(--color-border-2, #e5e7eb);
}

.preview-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

/* 变量下拉样式 */
.var-dropdown {
  width: 280px;
  max-height: 300px;
  overflow: hidden;
}
.var-pane {
  padding: 6px 10px;
  display: grid;
  grid-template-columns: 1fr;
  gap: 6px;
  max-height: 240px;
  overflow: auto;
}
.var-item {
  width: 100%;
  justify-content: flex-start;
  text-align: left;
}
.var-empty {
  padding: 12px;
  color: var(--color-text-3, #999);
}
</style>
